﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.Phone.Tasks;
using System.Collections.ObjectModel;
using Board1.Info;
using System.ComponentModel;
namespace Board1.UIPage
{
    public partial class ListResultSong : PhoneApplicationPage, INotifyPropertyChanged
    {
        public static int PageID;
        public static List<string> linkMP3;
        WebClient downloadPage = new WebClient();
        WebClient downloadXml = new WebClient();
        ZingSong selected = new ZingSong();
        public static ObservableCollection<ZingSong> selectedList;
        string webData = null, xmlFile = null;
        string xmlLink;
        public ListResultSong()
        {
            InitializeComponent();
            if (PageID == 0)
                result.ItemsSource = SongPage.ListResult;
            else
                result.ItemsSource = AlbumPage.ListResult;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            Busy = false; 
        } 

        // bat su kien khi chon 1 item trong list
        private void result_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            ListBoxItem item = this.result.ItemContainerGenerator.ContainerFromIndex(this.result.SelectedIndex) as ListBoxItem;
            int index = this.result.SelectedIndex;
            selectedList = new ObservableCollection<ZingSong>();
            linkMP3 = new List<string>();
            if (PageID == 0)
                selected = SongPage.ListResult[index];
            else 
                selected = AlbumPage.ListResult[index];
            DownloadHTML(selected.link);
        }

        //tai du lieu html cua noi dung bai hat lua chon
        private void DownloadHTML(string link)
        {
            try
            {
                downloadPage.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(DownloadStringCallback);
                downloadPage.DownloadStringAsync(new Uri(link));
            }
            catch (System.Exception)
            {
                MessageBox.Show("Internet Connection Error", "Error",MessageBoxButton.OK);
            }
        }

        private void DownloadStringCallback(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            LoadingState(true);
            webData = (string)e.Result;
            ThreadPool.QueueUserWorkItem(o =>
                {
                    Dispatcher.BeginInvoke(new Action(() => HtmlHandler(webData)));
                    Dispatcher.BeginInvoke(new Action(() => DownloadXML(xmlLink)));
                    Dispatcher.BeginInvoke(new Action(() => downloadPage.CancelAsync()));
                    Dispatcher.BeginInvoke(new Action(() =>  LoadingState(false)));
                    Thread.Sleep(3000);
                }
                );
          /*  HtmlHandler(webData);
            DownloadXML(xmlLink);
            downloadPage.CancelAsync();*/
        }

        // tai noi dung xml cua bai hat duoc chon
        private void DownloadXML(string link)
        {
            try
            {
                downloadXml.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadXMLCallback);
                downloadXml.DownloadStringAsync(new Uri(link));
            }
            catch(System.Exception)
            {
                MessageBox.Show("Internet Connection Error", "Error", MessageBoxButton.OK);
            }
        }
        private void DownloadXMLCallback(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            xmlFile = (string)e.Result;
            XmlHandler(xmlFile);
            //PlayMediaZing(link);
             
            this.NavigationService.Navigate(new Uri("/UIPage/MediaPlayer.xaml", UriKind.RelativeOrAbsolute));
            downloadXml.CancelAsync();
        }

        // xu li tim phan noi dung xml
        private void HtmlHandler(string data)
        {
            Match m = Regex.Match(data, "xmlUrl=(.*?)&amp", RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase);
            xmlLink = m.Groups[1].ToString();
        }

        //xu li noi dung xml tim kiem noi dung bai hat
        private void  XmlHandler(string data)
        {
            string link = null;
            MatchCollection m = Regex.Matches(data, "<item type=\"mp3\">(.*?)</item>", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
            foreach (Match n in m)
            {
                ZingSong temp = new ZingSong();
                string xml = n.Groups[1].ToString();
                Match m1= Regex.Match(xml,"<title>(.*?)</title>" ,RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
                temp.song = m1.Groups[1].ToString();
                temp.song = temp.song.Substring(9, temp.song.Length - 12);

                Match m2 = Regex.Match(xml, "<performer>(.*?)</performer>", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
                temp.artist = m2.Groups[1].ToString();
                temp.artist = temp.artist.Substring(9, temp.artist.Length - 12);

                Match m3 = Regex.Match(xml, "<source>(.*?)</source>", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
                link = m3.Groups[1].ToString();
                link = link.Substring(9, link.Length - 12);
                temp.link = link;

                temp.stateImg = "";

                selectedList.Add(temp);
                //XElement xmlsong = XElement.Parse(data);
                //var source = from e in xmlsong.Descendants("item"+ ) select link = xmlsong.Element("source").Value;
                linkMP3.Add(link);
            }
        }

        private void PlayMediaZing(string link)
        {
            MediaPlayerLauncher player = new MediaPlayerLauncher();
            player.Media = new Uri(link, UriKind.Absolute);
            player.Controls = MediaPlaybackControls.All;
            player.Location = MediaLocationType.Data;
            player.Show();
        }

        private bool busy;
        public bool Busy
        {
            get { return busy; }
            set
            {
                if (busy == value)
                {
                    return;
                }
                busy = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Busy"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            var tempEvent = PropertyChanged;
            if (tempEvent != null)
            {
                tempEvent(this, e);
            }
        }
        
        // tao trang thai loading tren man hinh
        private void LoadingState(bool e)
        {
            if (e)
            {
                LoadState.Visibility = Visibility.Visible;
                LoadBar.Visibility = Visibility.Visible;
                LoadBar.IsIndeterminate = e;
            }
            else 
            {
                LoadState.Visibility = Visibility.Collapsed;
                LoadBar.Visibility = Visibility.Collapsed;
                LoadBar.IsIndeterminate = e;
            }
        }
    }
}